# -*- coding: utf-8 -*-
from config import DEFAULT_USER_AVATAR_URL, DEFAULT_STUDIO_AVATAR_URL
from model.studio import Studio
from model.user import User


def clear_user():
    user_list = User.find({}, [
        User.Field.fan,
        User.Field.follow
    ])
    for user in user_list:
        fan_list = list(set(user.get(User.Field.fan)))
        follow_list = list(set(user.get(User.Field.follow)))
        User.collection.update({
            User.Field._id: user.get(User.Field._id)
        }, {
            '$set': {
                User.Field.fan: fan_list,
                User.Field.follow: follow_list
            }
        })


def clear_studio():
    studio_list = Studio.find({}, [
        Studio.Field.fan,
        Studio.Field.fanNum,
        Studio.Field.follow,
        Studio.Field.followNum,
    ])
    for studio in studio_list:
        fan_list = list(set(studio.get(Studio.Field.fan)))
        follow_list = list(set(studio.get(Studio.Field.follow)))
        Studio.collection.update({
            Studio.Field._id: studio.get(Studio.Field._id)
        }, {
            '$set': {
                Studio.Field.fan: fan_list,
                Studio.Field.follow: follow_list,
                Studio.Field.fanNum: len(fan_list),
                Studio.Field.followNum: len(follow_list)
            }
        })


def update_user_default_avatar():
    user_list = User.find({}, [
        User.Field.avatarUrl
    ])
    for user in user_list:
        if user.get(User.Field.avatarUrl) == '':
            User.collection.update({
                User.Field._id: user.get(User.Field._id)
            }, {
                '$set': {
                    User.Field.avatarUrl: DEFAULT_USER_AVATAR_URL
                }
            })


def update_studio_default_avatar():
    studio_list = Studio.find({}, [
        Studio.Field.avatarUrl
    ])
    for studio in studio_list:
        if studio.get(Studio.Field.avatarUrl) == '':
            Studio.collection.update({
                Studio.Field._id: studio.get(Studio.Field._id)
            }, {
                '$set': {
                    Studio.Field.avatarUrl: DEFAULT_STUDIO_AVATAR_URL
                }
            })


if __name__ == '__main__':
    print 'clearing'
    clear_user()
    clear_studio()
    update_studio_default_avatar()
    update_user_default_avatar()
